﻿#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;

class Student {
public:
	Student(const char * name, int age) {
		cout << "Student有参构造函数" << endl;
		if (name != NULL) {
			char * pName = (char *)malloc(strlen(name) + 1);
			strcpy(pName, name);
			this->pName = pName;
		}
		this->age = age; 
	}
	// 手动写拷贝构造函数，解决浅拷贝的问题 
	Student(const Student &s) {
		cout << "Student深拷贝构造函数" << endl;
		if (s.pName != NULL) {
			char * pName = (char *)malloc(strlen(s.pName) + 1);
			strcpy(pName, s.pName);
			this->pName = pName;
		}
		this->age = age;
	}
	~Student() {
		cout << "Student析构函数" << endl;
		if (pName != NULL) {
			free(pName);
		}
	}
public:
	char * pName;
	int age;
};

void test01() {
	Student s("小花", 10);
	Student s1(NULL, 10);
	Student s2(s); 
	cout << "s1 Name=" << s1.pName << ", s1 age=" << s1.age << endl;
	cout << "s2 Name=" << s2.pName << ", s2 age=" << s2.age << endl;
	// 调用析构函数时，先析构s1，s1.pName指向的内存被释放了，然后析构s2，由于默认的拷贝构造函数只是
	// 简单的赋值操作，s2.pName和s1.pName指向同一块内存，再次释放这块内存就报错了，这就是浅拷贝的问题。
}

int main()
{

	test01(); 

	system("pause");
	return EXIT_SUCCESS;
}